import notifacations from './notifacations'

let eventData: any = []
chrome.storage.local.get('eventData', (res) => {
  eventData = res.eventData || []
})
function createTab(url: string) {
  const createProperties = {
    url,
    active: false,
    pinned: true,
  }
  return new Promise((resolve) => {
    chrome.tabs.create(createProperties, async (tab) => {
      chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
        // console.log('createnew tab ', info)
        if (info.status === 'complete' && tabId === tab.id) {
          chrome.tabs.onUpdated.removeListener(listener)
          resolve(tab)
        }
      })
    })
  })
}
const monitorFn = (tabId: any, data: any) => {
  console.log(
    data.monitorName + '-监测开始',
    data,
    data.monitorInstance,
    data.monitorStatus
  )
  if (!data.monitorStatus) return
  chrome.scripting
    .executeScript({
      target: { tabId },
      func: () => {
        return document.documentElement.outerHTML
      },
    })
    .then((result: any) => {
      // compare
      if (result[0] && result[0].result) {
        const documentOuterHTML = result[0].result
        const replacedOuterHTML = documentOuterHTML.toString()
        console.log('getpage data----:')
        // console.log(documentOuterHTML, data.outerHTML)
        // console.dir(documentOuterHTML)
        // console.log(replacedOuterHTML, data.outerHTML)
        const compareResult = replacedOuterHTML.includes(data.outerHTML)
        console.log(data.monitorName + '-比对结果:', compareResult)
        if (!compareResult) {
          notifacations.create(`[${data.monitorName}]监控`, '页面有变化')
        }
        chrome.tabs.remove(tabId, function () {
          console.log('remove:', tabId)
        })
        console.log('==============================')
      }
    })
  if (!data.monitorStatus) {
    data.monitorInstance = null
    data.monitorStatus = false
    clearInterval(data.monitorInstance)
  } else {
    intervalMonitor(tabId, data)
  }
}
const monitorFnNew = async (tabId: any, data: any) => {
  // console.log(data.monitorName + '-监测开始', data, data.monitorInstance, data.monitorStatus)
  let tab: any = await createTab(data.url)
  console.log('new tab', tab)
  const newTabId = tab.id
  data.id = newTabId
  monitorFn(newTabId, data)
}
const intervalMonitor = (tabId: any, data: any) => {
  data.monitorInstance = setTimeout(
    monitorFnNew,
    Number(data.monitorInterval) * 1.5 * 1000 || 5 * 60 * 1000,
    tabId,
    data
  )
}
export default {
  startMonitor: (index: number) => {
    const data = eventData[index]
    const tabId = data.id
    data.monitorStatus = true
    intervalMonitor(tabId, data)
    // data.monitorInstance = setInterval(monitorFn, Number(data.monitorInterval) * 1.5 * 1000 || 5 * 60 * 1000, tabId, data)
    chrome.storage.local.set({ eventData })
    // notifacation
    // notifacations.create(`[${data.monitorName}]监控`, '监控已开启')
  },
  addMonitor: (data: any) => {
    console.log('addMonitor', data, data.class)
    const tabId = data.id
    // pin tab   todo:options
    chrome.tabs.update(tabId, { pinned: true })
    // set monitor
    data.monitorStatus = true
    intervalMonitor(tabId, data)
    // data.monitorInstance = setInterval(monitorFn, Number(data.monitorInterval) * 1.5 * 1000 || 5 * 60 * 1000, tabId, data)
    // const storageData = Object.assign({}, data, {monitorInstance: null})
    chrome.storage.local.get('eventData', (res) => {
      eventData = res.eventData || []
      console.log('eventData', res, eventData)
      // if (eventData) {
      eventData.push(data)
      // }
      chrome.storage.local.set({ eventData })
    })
    // notifacation
    // notifacations.create(`[${data.monitorName}]监控`, '监控已开启')
    // notifacations.create('监控:', '监控已开启')
  },
  pauseMonitor: (index: number) => {
    console.log('pauseMonitor', index, eventData[index])
    eventData[index].monitorInstance = null
    eventData[index].monitorStatus = false
    clearInterval(eventData[index].monitorInstance)
    chrome.storage.local.set({ eventData })
  },
  clearMonitor: () => {
    console.log('clearMonitor')
    eventData.forEach((item: any) => {
      clearInterval(item.monitorInstance)
      item.monitorInstance = null
      item.monitorStatus = false
      chrome.storage.local.set({ eventData })
    })
  },
  deleteMonitor: (index: number) => {
    console.log('deleteMonitor', eventData, index)
    eventData[index].monitorInstance = null
    eventData[index].monitorStatus = false
    clearInterval(eventData[index].monitorInstance)
    eventData.splice(index, 1)
    return chrome.storage.local.set({ eventData })
  },
  clearEvent: () => {
    console.log('clearEvent')
    eventData = []
    chrome.storage.local.set({ eventData })
  },
}
